import cv2
import numpy as np

# 读取图片
image = cv2.imread("/Users/lanyanhua/Downloads/6e34f99bcba0c610e67e56b9a0fc778c.jpg")

# 转换为灰度图像
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 进行二值化处理
ret, binary_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)

# 查找轮廓
contours, hierarchy = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 创建一个与原图大小相同的黑色图像作为蒙版
mask = np.zeros_like(image)

# 在蒙版上绘制轮廓
cv2.drawContours(mask, contours, -1, (255, 255, 255), thickness=-1)

# 将原始图像应用到蒙版上
result = cv2.bitwise_and(image, image, mask=mask)

# 显示结果
cv2.imshow("Result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 保存结果
cv2.imwrite("/Users/lanyanhua/Downloads/6e34f99bcba0c610e67e56b9a0fc778c111.png", result)